<script lang="ts" setup>
import { filterTree } from '@/utils/dept'
import { transformI18n } from '@/plugins/i18n'
import type { SysDeptListType } from '@/views/admin/system/dept/utils/model'

type Props = {
  data: SysDeptListType[]
}
// 接收父组件传参
const props = defineProps<Props>()
const emit = defineEmits<{
  /**
   * 选择部门树
   * @param e
   * @param value 选中的部门id
   */
  (e: 'selectTree', value: number | undefined)
}>()
// 部门树
const treeData = ref<SysDeptListType[]>([])
// 部门树副本
const treeDataTemp = ref<SysDeptListType[]>([])
// 树形结构配置
const fieldNames = {
  children: 'children',
  title: 'deptName',
  key: 'id'
}
const themeToken = getThemeTokenHook()
//搜索值
const searchValue = ref<string>('')
// 监听父组件传参
watch(
  () => props,
  () => {
    treeData.value = props.data
    treeDataTemp.value = props.data
  },
  {
    deep: true
  }
)

// 选择部门树
function selectTree(selectedKeys) {
  emit('selectTree', selectedKeys[0])
}

// 监听搜索
watch(searchValue, (newVal) => {
  treeData.value = filterTree(treeDataTemp.value as SysDeptListType[], newVal)
})
</script>
<template>
  <div
    :style="{
      background: themeToken.colorBgContainer,
      padding: '10px',
      borderRadius: themeToken.borderRadius + 'px',
      boxShadow: themeToken.boxShadowTertiary
    }"
  >
    <a-input
      v-model:value="searchValue"
      :placeholder="transformI18n('tree.search')"
      style="margin-bottom: 8px"
    >
      <template #suffix>
        <Icon style="font-size: 20px" type="icon-search" />
      </template>
    </a-input>
    <a-tree
      v-if="treeData.length"
      :fieldNames="fieldNames"
      :tree-data="treeData"
      defaultExpandAll
      show-icon
      @select="selectTree"
    >
      <template #title="{ deptName }">
        <!-- 解决搜索高亮文字有间隔 -->
        <template v-if="deptName.indexOf(searchValue) > -1">
          <span>{{ deptName.substring(0, deptName.indexOf(searchValue)) }}</span>
          <span
            :style="{
              color: themeToken.colorError
            }"
            >{{ searchValue }}</span
          >
          <span>{{ deptName.substring(deptName.indexOf(searchValue) + searchValue.length) }}</span>
        </template>
        <span v-else>{{ deptName }}</span>
      </template>
      <template #icon="{ key, selected }">
        <Icon type="icon-branches" />
      </template>
    </a-tree>
  </div>
</template>
